package gain

import (
	"log"
	"proxy_pool/entity"
	"strconv"
	"strings"
	"time"

	"github.com/PuerkitoBio/goquery"
	"github.com/parnurzeal/gorequest"
)

func Kuaidl() (result []*entity.IPEntity) {
	for i := 1; i < 6; i++ {
		pUrl := "https://www.kuaidaili.com/free/inha/" + strconv.Itoa(i) + "/"
		time.Sleep(10 * time.Second)
		data := dealKdlIp(pUrl)
		if len(data) > 0 {
			for i := 0; i < len(data); i++ {
				result = append(result, data[i])
			}
		}
	}
	return
}

func dealKdlIp(pollURL string) (result []*entity.IPEntity) {
	resp, _, errs := gorequest.New().Get(pollURL).End()
	if errs != nil {
		log.Println("kdl请求错误信息：", errs)
		return
	}
	if resp.StatusCode != 200 {
		log.Println("kdl请求失败信息：", errs)
		return
	}
	// fmt.Println(resp.Body)
	doc, err := goquery.NewDocumentFromReader(resp.Body)
	resp.Body.Close()
	if err != nil {
		log.Println("kdl请求页面失败信息：", err.Error())
		return
	}
	doc.Find("table>tbody>tr").Each(func(i int, s *goquery.Selection) {
		// log.Println(s.Text())
		ip := s.Find("td:nth-child(1)").Text()
		port := s.Find("td:nth-child(2)").Text()
		ipType := s.Find("td:nth-child(4)").Text()
		location := s.Find("td:nth-child(5)").Text()
		speedStr := s.Find("td:nth-child(6)").Text()
		speed := strings.TrimRight(speedStr, "秒")
		lastTime := s.Find("td:nth-child(7)").Text()

		InitIP := entity.InitIPEntity()
		InitIP.Ip = ip
		InitIP.Port = port
		InitIP.IpType = ipType
		InitIP.Location = location
		InitIP.Speed = speed
		InitIP.LastTime = lastTime
		result = append(result, InitIP)
	})
	log.Println(pollURL + "   finish!!! ")
	return
}
